import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import CategoryMore from '../views/CategoryMore.vue'
import SearchResults from '@/views/SearchResults.vue'
import ImageComposer from '@/components/ImageComposer.vue'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err
    }
  })
}

// 创建标题管理器
class TitleManager {
  constructor() {
    this._siteTitle = ''
  }

  get siteTitle() {
    return this._siteTitle
  }

  setSiteTitle(title) {
    this._siteTitle = title
    // 更新当前页面标题
    const currentRoute = router.currentRoute
    if (currentRoute && currentRoute.meta && currentRoute.meta.title) {
      this.resolveTitle(currentRoute.meta.title)
    }
  }

  resolveTitle(pageTitle) {
    document.title = this.siteTitle ? `${pageTitle} - ${this.siteTitle}` : pageTitle
  }
}

export const titleManager = new TitleManager()

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      title: '首页'
    }
  },
  {
    path: '/category/:id',
    name: 'CategoryMore',
    component: CategoryMore,
    meta: {
      title: '分类详情'
    }
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: () => import('@/views/Detail.vue'),
    meta: {
      title: '详情'
    }
  },
  {
    path: '/search',
    name: 'SearchResults',
    component: SearchResults,
    meta: {
      title: '搜索结果'
    }
  },
  {
    path: '/image-composer',
    name: 'ImageComposer',
    component: ImageComposer,
    meta: {
      title: '图片合成工具'
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    titleManager.resolveTitle(to.meta.title)
  }
  next()
})

export default router
